package com.study.doc;

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class MergeWordDocuments {

    public static void main(String[] args) {
        String[] inputFiles = {"D:\\学习资料\\jdk\\文件合并\\a.docx", "D:\\学习资料\\jdk\\文件合并\\b.docx"};
        String outputFile = "D:\\学习资料\\jdk\\文件合并\\c.docx";

        try {
            XWPFDocument mergedDocument = new XWPFDocument();

            for (String file : inputFiles) {
                FileInputStream fis = new FileInputStream(file);
                XWPFDocument document = new XWPFDocument(fis);
                appendDocument(mergedDocument, document);
                fis.close();
            }

            FileOutputStream fos = new FileOutputStream(outputFile);
            mergedDocument.write(fos);
            fos.close();

            System.out.println("Documents merged successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void appendDocument(XWPFDocument mergedDocument, XWPFDocument document) {
        for (IBodyElement element : document.getBodyElements()) {
            if (element instanceof XWPFParagraph) {
                mergedDocument.createParagraph().createRun().setText(((XWPFParagraph) element).getText());
            } else if (element instanceof XWPFTable) {
                XWPFTable table = (XWPFTable) element;
                XWPFTable newTable = mergedDocument.createTable();
                copyTable(table, newTable);
            }
        }
    }

    private static void copyTable(XWPFTable sourceTable, XWPFTable targetTable) {
        for (XWPFTableRow sourceRow : sourceTable.getRows()) {
            XWPFTableRow targetRow = targetTable.createRow();
            for (int i = 0; i < sourceRow.getTableCells().size(); i++) {
                XWPFTableCell sourceCell = sourceRow.getCell(i);
                XWPFTableCell targetCell = targetRow.addNewTableCell();
                targetCell.setText(sourceCell.getText());
            }
        }
    }
}
